package com.gfilechooser;

import java.io.File;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentManager.BackStackEntry;
import android.support.v4.app.FragmentManager.OnBackStackChangedListener;
import android.support.v4.app.FragmentTransaction;
import android.widget.Toast;

/**
 * @author Guillermo
 * 
 */

public class FileChooserActivity extends FragmentActivity implements
		OnBackStackChangedListener {

	public static final String PATH = "path";
	public static final String EXTERNAL_BASE_PATH = Environment
			.getExternalStorageDirectory().getAbsolutePath();

	private FragmentManager fragmentManager;
	private BroadcastReceiver storageListener = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			Toast.makeText(context, R.string.storage_removed, Toast.LENGTH_LONG)
					.show();
			finishWithResult(null);
		}
	};

	private String path;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_file_chooser);
		fragmentManager = getSupportFragmentManager();
		fragmentManager.addOnBackStackChangedListener(this);
		if (savedInstanceState == null) {
			path = EXTERNAL_BASE_PATH;
			addFragment(path);
		} else {
			path = savedInstanceState.getString(PATH);
		}
		setTitle(path);
	}

	@Override
	protected void onPause() {
		super.onPause();
		unregisterStorageListener();
	}

	@Override
	protected void onResume() {
		super.onResume();
		registerStorageListener();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putString(PATH, path);
	}

	@Override
	public void onBackStackChanged() {
		path = EXTERNAL_BASE_PATH;
		int count = fragmentManager.getBackStackEntryCount();
		if (count > 0) {
			BackStackEntry fragment = fragmentManager
					.getBackStackEntryAt(count - 1);
			path = fragment.getName();
		}
		setTitle(path);
	}

	private void addFragment(String path) {
		FileListFragment explorerFragment = FileListFragment.newInstance(path);
		fragmentManager.beginTransaction()
				.add(R.id.explorer_fragment, explorerFragment).commit();
	}

	private void replaceFragment(String path) {
		FileListFragment explorerFragment = FileListFragment.newInstance(path);
		fragmentManager.beginTransaction()
				.replace(R.id.explorer_fragment, explorerFragment)
				.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
				.addToBackStack(path).commit();
	}

	private void finishWithResult(File file) {
		if (file != null) {
			Uri uri = Uri.fromFile(file);
			setResult(RESULT_OK, new Intent().setData(uri));
			finish();
		} else {
			setResult(RESULT_CANCELED);
			finish();
		}
	}

	protected void onFileSelected(File file) {
		if (file != null) {
			path = file.getAbsolutePath();
			if (file.isDirectory()) {
				replaceFragment(path);
			} else {
				finishWithResult(file);
			}
		} else {
			Toast.makeText(FileChooserActivity.this,
					R.string.error_selecting_file, Toast.LENGTH_SHORT).show();
		}
	}

	private void registerStorageListener() {
		IntentFilter filter = new IntentFilter();
		filter.addAction(Intent.ACTION_MEDIA_REMOVED);
		registerReceiver(storageListener, filter);
	}

	private void unregisterStorageListener() {
		unregisterReceiver(storageListener);
	}
}
